ResourceLoader
接口是由可以返回(即加载)Resource
实例的对象实现的。
public interface ResourceLoader {
Resource getResource(String location);
}
所有的应用程序上下文都实现了ResourceLoader
的接口,因此所有的应用程序上下文都可以用来获取Resource
实例。
当您在特定的应用程序上下文中调用getResource()
,并且指定的位置路径没有特定的前缀时,将返回适合该特定应用程序上下文的Resource
类型。例如,假设下面的代码片段是针对ClassPathXmlApplicationContext
实例执行的:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
返回的将是ClassPathResource
;如果同样的代码是由FileSystemXmlApplicationContext
实例执行的,FileSystemResource
将被返回。如果是WebApplicationContext
,那么就是ServletContextResource
,等等。
因此,您可以以适合特定应用程序上下文的方式加载资源。
另外,你可以通过制定特殊的classpath:
前缀来强制得到ClasspathResource
,而不管应用程序的类型是什么:
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
类似的,你可以通过制定标准的java.net.URL
前缀强制得到UrlResoucre
:
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
以下表格总结了String
和Resource
的转换关系:
表8.1 Resource String
前缀 | 例子 | 说明 |
---|---|---|
classpath: | classpath:com/myapp/config.xml |
从类路径下加载 |
file: | file:///data/config.xml |
从文件系统中作为URL 加载[1] |
http: | http://myserver/logo.png |
作为URL 加载 |
(none) | /data/config.xml |
取决于ApplicationCOntext |
[1]见7.7.3 "FileSystem caveats"。 |